﻿/*****************************************介绍*****************************************
 * 作者：User
 * 创建时间：2025-09-08 18:45:42
 * 功能：UGUI通用画线组件
 * 版本：V1.0.0
**************************************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Game.UI
{
    [RequireComponent(typeof(RectTransform))]
    public class UILineRenderer : MonoBehaviour
    {
        [Header("Line Settings")]
        public float lineWidth = 14f;

        [Header("Line Type")]
        public Image.Type lineType = Image.Type.Filled;

        [Header("Animation Settings")]
        public float animationDuration = .5f;
        public AnimationCurve animationCurve = AnimationCurve.Linear(0, 0, 1, 1);

        private List<Image> m_LineSegments = new List<Image>();
        private List<float> m_LineWidths = new List<float>();
        private Coroutine m_AnimationCoroutine;
        private ILineObj m_LineObjMgr;

        public void Init(ILineObj lineObj)
        {
            m_LineObjMgr = lineObj;
        }

        /// <summary>
        /// 绘制线条
        /// </summary>
        /// <param name="points">UI空间中的点列表</param>
        /// <param name="animate">是否播放动画</param>
        public void DrawLine(List<Vector2> points, bool animate = true, Action<bool> complate = null)
        {
            if (m_LineObjMgr == null)
            {
                Debug.LogError("请先进行初始化，调用Init函数");
                return;
            }

            // 清除之前的线条
            ClearLine();

            if (points == null || points.Count < 2)
            {
                Debug.LogWarning("需要至少两个点来绘制线条");
                complate?.Invoke(false);
                return;
            }

            // 创建线条段
            for (int i = 0; i < points.Count - 1; i++)
            {
                bool isLengthen = i + 1 < points.Count - 1;
                CreateLineSegment(points[i], points[i + 1], isLengthen);
            }

            // 播放动画
            if (animate && gameObject.activeInHierarchy)
            {
                if (m_AnimationCoroutine != null)
                    StopCoroutine(m_AnimationCoroutine);

                m_AnimationCoroutine = StartCoroutine(AnimateLine(complate));
            }
            else
            {
                // 不播放动画，直接显示完整线条
                ShowAllLines();
                complate?.Invoke(true);
            }
        }

        private void ShowAllLines()
        {
            for (int i = 0; i < m_LineSegments.Count; i++)
            {
                if (lineType == Image.Type.Filled)
                    m_LineSegments[i].fillAmount = 1f;
                else
                {
                    float width = m_LineWidths[i];
                    m_LineSegments[i].rectTransform.sizeDelta = new Vector2(width, lineWidth);
                    m_LineSegments[i].gameObject.SetActive(true);
                }
            }
        }

        /// <summary>
        /// 清除所有线条
        /// </summary>
        public void ClearLine()
        {
            if (m_LineObjMgr == null)
            {
                Debug.LogError("请先进行初始化，调用Init函数");
                return;
            }

            if (m_AnimationCoroutine != null)
            {
                StopCoroutine(m_AnimationCoroutine);
                m_AnimationCoroutine = null;
            }

            foreach (var segment in m_LineSegments)
            {
                if (segment != null && segment.gameObject != null)
                    m_LineObjMgr.Delete(segment.gameObject);
            }

            m_LineSegments.Clear();
            m_LineWidths.Clear();
        }

        /// <summary>
        /// 创建单个线条段
        /// </summary>
        private void CreateLineSegment(Vector2 startPoint, Vector2 endPoint, bool lengthen = false)
        {
            // 计算线段的方向和长度
            Vector2 direction = endPoint - startPoint;
            float distance = direction.magnitude;
            float angle = Mathf.Atan2(direction.y, direction.x) * Mathf.Rad2Deg;

            var segmentObj = m_LineObjMgr.Get();
            segmentObj.transform.SetParent(transform);
            segmentObj.transform.localScale = Vector3.one;
            segmentObj.rectTransform.anchoredPosition3D = Vector3.zero;

            // 添加Image组件
            segmentObj.raycastTarget = false;
            segmentObj.type = lineType;
            if (lineType == Image.Type.Filled)
            {
                segmentObj.fillMethod = Image.FillMethod.Horizontal;
                segmentObj.fillOrigin = 0; // 从左到右填充
                segmentObj.fillAmount = 0f; // 初始不可见
            }

            // 设置RectTransform
            float width = lengthen ? distance + lineWidth * .5f : distance;
            segmentObj.rectTransform.sizeDelta = new Vector2(width, lineWidth);

            // 设置锚点
            segmentObj.rectTransform.anchorMin = Vector2.zero;
            segmentObj.rectTransform.anchorMax = Vector2.zero;
            segmentObj.rectTransform.pivot = Vector2.up * 0.5f;
            segmentObj.rectTransform.anchoredPosition = startPoint;
            segmentObj.rectTransform.localRotation = Quaternion.Euler(0, 0, angle);

            if (lineType == Image.Type.Tiled)
                segmentObj.gameObject.SetActive(false);

            m_LineSegments.Add(segmentObj);
            m_LineWidths.Add(width);
        }

        /// <summary>
        /// 线条动画协程
        /// </summary>
        private IEnumerator AnimateLine(Action<bool> complate)
        {
            float elapsedTime = 0f;

            while (elapsedTime < animationDuration)
            {
                float t = animationCurve.Evaluate(elapsedTime / animationDuration);

                for (int i = 0; i < m_LineSegments.Count; i++)
                {
                    // 计算每个线段的填充量
                    float segmentProgress = Mathf.Clamp01((t - (i / (float)m_LineSegments.Count)) * m_LineSegments.Count);
                    if (lineType == Image.Type.Filled)
                        m_LineSegments[i].fillAmount = segmentProgress;
                    else
                    {
                        m_LineSegments[i].rectTransform.sizeDelta = new Vector2(m_LineWidths[i] * segmentProgress, lineWidth);
                        if (!m_LineSegments[i].gameObject.activeSelf && segmentProgress > 0)
                            m_LineSegments[i].gameObject.SetActive(true);
                    }
                }

                elapsedTime += Time.deltaTime;
                yield return null;
            }

            // 确保所有线段都完全显示
            ShowAllLines();

            m_AnimationCoroutine = null;
            complate?.Invoke(true);
        }
    }

    public interface ILineObj
    {
        Image Get();
        void Delete(GameObject line);
    }
}